<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Auth\AuthenticationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use App\Helpers\Code;

class ExceptionReport
{

    /**
     * @var Exception
     */
    public $exception;

    /**
     * @var Request
     */
    public $request;

    /**
     * @var
     */
    protected $report;
    protected $result = [
        'code' => Code::SYSTEM_OK,
        'data' => [],
        'msg' => []
    ];

    /**
     * @var array
     */
    public $doReport = [
        AuthenticationException::class => ['未授权', Code::SYSTEM_UNAUTHORIZED],
        NotFoundHttpException::class => ['未定义', Code::SYSTEM_CONFINE_ERROR]
    ];

    /**
     * ExceptionReport constructor.
     * @param Request $request
     * @param Exception $exception
     */
    function __construct(Request $request, Exception $exception)
    {
        $this->request = $request;
        $this->exception = $exception;
    }

    /**
     * @return bool
     */
    public function shouldReturn()
    {
        foreach (array_keys($this->doReport) as $report) {

            if ($this->exception instanceof $report) {

                $this->report = $report;
                return true;
            }
        }

        return false;
    }

    /**
     * @param Exception $e
     * @return static
     */
    public static function make(Exception $e)
    {

        return new static(\request(), $e);
    }

    /**
     * @return mixed
     */
    public function report()
    {
        $message = $this->doReport[$this->report];

        $this->result['code'] = $message[1];
        $this->result['msg'] = $message[0];

        return Response::json($this->result);
    }

}
